package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserFavor;
import cn.wolfcode.wolf2w.redis.service.IStatisVORedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IUserFavorService;
import cn.wolfcode.wolf2w.vo.StrategyStatisVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {


    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStatisVORedisService statisVORedisService;

    @Autowired
    private IUserFavorService userFavorService;

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        System.out.println("---------------------statisVo初始化starting------------------------");


        // 将数据库的所有攻略数据拿到
        List<Strategy> list = strategyService.list();
        // 如何将 mongodb ---> redis
        // 遍历 list
        for (Strategy strategy : list) {
           // 通过 strategy 的id 拼接缓存到redis的key
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.getId());
            // 判断redis缓存中是否有该key, 有的话就不初始化, 不再进行二次初始化
            if(template.hasKey(key)) {
                // 跳过, 不缓存到Redis中
                continue;
            }
            // 拿到对应的vo
            StrategyStatisVo vo = statisVORedisService.getStrategyStatisVoById(strategy.getId());
            // 将key 与 vo 对应起来 形成 键值对
            // 把键值对插入到缓存当中
            statisVORedisService.setStrategyStatisVo(vo);
        }


        List<UserFavor> userFavors = userFavorService.list();
        for (UserFavor userFavor : userFavors) {
            // 拼接每一个key user--favor的key
            String key = RedisKeys.USER_FAVOR_STRATEGY.join(userFavor.getUserId());
            // 如果有该key 就跳过, 不进行初始化
            if (template.hasKey(key)){
                continue;
            }
            template.opsForValue().set(key, JSON.toJSONString(userFavor.getStrategyIds()));
        }


        System.out.println("---------------------statisVo初始化ending------------------------");

    }
}
